package cn.org.donald.framework.interceptor;

import cn.org.donald.framework.pojo.dto.RequestInfo;
import cn.org.donald.framework.util.BeanUtil;
import cn.org.donald.framework.util.RequestUtil;
import cn.org.donald.framework.service.ServletRequestService;
import org.apache.dubbo.config.annotation.Reference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author : Donald
 * @since : 2020/12/16 17:03
 */
@Configuration
public class WebInterceptor implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(WebInterceptor.class);

    @Reference(version = "1.0.0",group = "donald")
    private ServletRequestService servletRequestService;

    @Autowired
    private RequestInfo requestInfo;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            String userId = request.getHeader("userId");
            String ip = RequestUtil.getRealIp(request);
            String authorization = request.getHeader("authorization");
            RequestInfo requestInfo = new RequestInfo();
            requestInfo.setAuthorization(authorization);
            requestInfo.setUserId(Long.parseLong(userId));
            requestInfo.setIp(ip);
            // 本地注入
            BeanUtil.copyProperties(requestInfo,this.requestInfo);

            // 远程注入
            boolean b = servletRequestService.setRequestBody(requestInfo);
            logger.debug("注入"+ (b?"成功!":"失败!"));
            return true;
        }catch (Exception e){
            logger.debug("request参数为空!");
            return true;
        }
    }
}
